/**
* 学生进行考试
**/ 

<template>
  <div>
    <el-container>
      <el-main>
        <!-- 考试题目显示内容走马灯显示 -->
        <el-main>
          <template>
            <el-carousel ref="carousel"
                         indicator-position="none"
                         height="700px"
                         :autoplay="false"
                         arrow="never"
                         :loop="false">
              <el-carousel-item v-for="item in this.paperitem"
                                :key="item.id">
                <h2>第{{item.i + 1}}题</h2>
                <el-descriptions title=""
                                 v-if="item.text">
                  <el-descriptions-item label="阅读">{{item.text}}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="">
                  <el-descriptions-item label="题干">{{item.topic}}</el-descriptions-item>
                </el-descriptions>
                <el-radio-group v-model="opt"
                                @change="change(item.id)"
                                type="vertical"
                                v-if="item.typeid == 1 | item.typeid == 5">
                  <el-radio :label="a.id"
                            v-for="a in item.opList"
                            :key="a.id">{{a.opt}}</el-radio>
                </el-radio-group>
                <el-checkbox-group v-model="opts"
                                   @change="checkchange(item.id)"
                                   v-if="item.typeid == 2">
                  <el-checkbox v-for="b in item.opList"
                               :label="b.id"
                               :key="b.id">{{b.opt}}</el-checkbox>
                </el-checkbox-group>

                <el-button type="primary"
                           icon="el-icon-caret-left"
                           @click="showstep(item.i - 1)">上一题</el-button>

                <el-button type="primary"
                           icon="el-icon-caret-right"
                           @click="showstep(item.i + 1)">下一题</el-button>
              </el-carousel-item>

            </el-carousel>
          </template>
        </el-main>
      </el-main>
      <el-aside width="300px">
        <el-container>
          <el-header height="270px">
            <template>
              <div>
                <label>考生:</label><br />{{this.username}}
                <el-divider content-position="left"></el-divider>
                <label>总分</label>{{this.result.score}}
                <el-divider><i class=""></i></el-divider>
                <h5>剩余时间</h5>{{this.endtime}}
                <el-divider content-position="right"></el-divider>
              </div>
            </template>
          </el-header>
          <el-main>
            <el-collapse v-model="activeNames"
                         @change="handleChange"
                         accordion>
              <el-collapse-item title="单选题"
                                name="1">
                <div v-for="item in this.paperitem"
                     :key="item.id">
                  <el-button type="info"
                             @click="showstep(item.i)"
                             plain
                             v-if="item.typeid == 1">{{item.i + 1}}</el-button>
                </div>
              </el-collapse-item>
              <el-collapse-item title="多选题"
                                name="2">
                <div v-for="item in this.paperitem"
                     :key="item.id">
                  <el-button type="info"
                             @click="showstep(item.i)"
                             plain
                             v-if="item.typeid == 2">{{item.i + 1}}</el-button>
                </div>
              </el-collapse-item>
              <el-collapse-item title="阅读题"
                                name="5">
                <div v-for="item in this.paperitem"
                     :key="item.id">
                  <el-button type="info"
                             @click="showstep(item.i)"
                             plain
                             v-if="item.typeid == 5">{{item.i + 1}}</el-button>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-main>
        </el-container>
        <el-button type="primary"
                   @click="submit">提交试卷<i class="el-icon-upload el-icon--right"></i></el-button>
      </el-aside>
    </el-container>
  </div>
</template>

<script>
// 导入组件
import { submitExam } from '../../api/exam'
// 导出模块
export default {
  // 模块名字
  name: 'template',
  // 模块数据
  data() {
    //数据
    return {
      //折叠面板属性
      activeNames: ['1'],
      //试卷信息
      paperitem: {
        id: '',
        i: 0,
      },
      result: {
        result: {},
        uid: '',
        pid: '',
        score: 0,
        userscore: 0,
      },
      opt: '',
      opts: [],
      username: '',
      //考试结束时间
      endtime: '',
      //倒计时定时器
      timer: '',
      //保存this.paperitem的数组形式
      paperitem2: [],
    }
  },
  // 注册组件
  components: {
    // headerComponent
  },
  // 监听指定值，只有指定值变化，才会触发
  watch: {},
  // 里面的函数只有调用才会执行（实时计算）里面是定义的方法
  methods: {
    //折叠面板改变时执行的方法
    handleChange(val) {},
    //单选框发生变化时执行的方法
    change(parameter) {
      let currentscore = 0
      for (var a in this.paperitem[parameter].opList) {
        if (this.paperitem[parameter].opList[a].status == 'y') {
          if (this.paperitem[parameter].opList[a].id == this.opt) {
            currentscore = this.paperitem[parameter].score
          } else {
            currentscore = 0
          }
        }
      }
      this.result.result[parseInt(parameter)] = {
        opt: this.opt,
        score: currentscore,
      }
      // console.log(this.result.result)
    },
    //多选框发生变化时执行的方法
    checkchange(value) {
      let currentscore = 0
      let answeropt = []
      //取得正确答案长度，以及正确答案的数组id
      let answerlength = 0
      for (var a in this.paperitem[value].opList) {
        if (this.paperitem[value].opList[a].status == 'y') {
          answerlength = answerlength + 1
          answeropt.push(this.paperitem[value].opList[a].id)
        }
      }
      //取出所选答案的数组
      if (this.opts.length == answerlength) {
        //用i标记所选答案在正确答案中的个数
        let i = 0
        for (var a in this.opts) {
          if (answeropt.indexOf(this.opts[a]) != -1) {
            i++
          }
        }
        if (i == answerlength) {
          currentscore = this.paperitem[value].score
        } else {
          currentscore = 0
        }
      }
      this.result.result[parseInt(value)] = {
        opt: this.opts,
        score: currentscore,
      }
      // console.log(this.result.result)
    },
    //跳转走马灯页面
    showstep(ind) {
      this.$refs.carousel.setActiveItem(ind)
      this.memory(ind)
    },
    //时间戳转换为时分秒
    toHHmmss(date) {
      var time
      var hours = parseInt((date % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      var minutes = parseInt((date % (1000 * 60 * 60)) / (1000 * 60))
      var seconds = parseInt((date % (1000 * 60)) / 1000)
      time =
        (hours < 10 ? '0' + hours : hours) +
        '时' +
        (minutes < 10 ? '0' + minutes : minutes) +
        '分' +
        (seconds < 10 ? '0' + seconds : seconds + '秒')
      return time
    },
    //监听事件
    memory(parameter) {
      //找到当前页面题目的id
      let currentid = this.paperitem2[parameter].id
      //取出当前页面题目的选项
      if (this.paperitem2[parameter].typeid == 2) {
        this.opts = []
        if (this.result.result[currentid]) {
          this.opts = this.result.result[currentid].opt
        }
      } else {
        if (this.result.result[currentid]) {
          this.opt = this.result.result[currentid].opt
        }
      }
    },
    //提交试卷，保存考生答案至数据库
    submit() {
      for(var key in this.result.result){
        this.result.userscore = this.result.result[key].score + this.result.userscore
      }
      submitExam(this.result).then((res) => {
        console.log(res)
      })
      alert("当前考试已结束！！！")
      this.$router.push({ path: '/system/joinExam' })
    },
  },
  // 创建前状态(里面是操作)
  beforeCreate() {},
  // 创建完毕状态(里面是操作)
  created() {
    let i = 0
    //格式化试卷详情信息
    for (let key in JSON.parse(localStorage.getItem('paperItem'))) {
      if (this.paperitem.i == 0) {
        this.paperitem = JSON.parse(localStorage.getItem('paperItem'))
      }
      this.result.score = this.result.score + this.paperitem[key]['score']
      this.paperitem[key]['id'] = key
      this.paperitem[key]['i'] = i
      i++
    }
    //将paperitem转换为数组保存起来
    for (let key in this.paperitem) {
      this.paperitem2.push(this.paperitem[key])
    }
    //获取当前学生信息
    this.username = JSON.parse(localStorage.getItem('userdata')).data.username
    //获取学生id
    this.result.uid = JSON.parse(localStorage.getItem('userdata')).data.id
    //自定义定时器，倒计时为距离考试结束的时间
    if (true) {
      let b = this
      this.timer = setInterval(function () {
        b.endtime =
          new Date(
            b
              .$moment(b.$store.state.endtime['endtime'])
              .format('YYYY-MM-DD HH:mm:ss')
          ).getTime() - new Date().getTime()
        b.endtime = b.toHHmmss(b.endtime)
      }, 1000)
      b.result.pid = b.$store.state.paperid.paperid
    }
  },
  // 挂载前状态(里面是操作)
  beforeMount() {},
  // 挂载结束状态(里面是操作)
  mounted() {},
  // 更新前状态(里面是操作)
  beforeUpdate() {},
  // 更新完成状态(里面是操作)
  updated() {},
  // 销毁前状态(里面是操作)
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer) // 在Vue实例销毁前，清除我们的定时器
    }
  },
  // 销毁完成状态(里面是操作)
  destroyed() {},
}
</script>
// scoped 样式只在本组件使用
<style scoped>
/**
 * 导入css样式组件
 * @import "../assets/css/components/index.css";
 */
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-radio__label {
  text-overflow: ellipsis;
  white-space: normal;
  line-height: 18px;
  vertical-align: middle;
  display: inline-block;
}
</style>